package com.cskaoyan.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.exception.ValidateException;
import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.commons.util.jwt.AESUtil;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.entitys.UserVerify;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dal.persistence.UserVerifyMapper;
import com.cskaoyan.user.form.UserRegisterRequest;
import com.cskaoyan.user.form.UserVerifyRequest;
import com.cskaoyan.user.service.IUserRegisterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.validation.constraints.NotEmpty;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author 2731235517@qq.com 谢畅
 * @since 2023/01/09 22:25
 */
@Service
@Transactional
@Slf4j
public class UserRegisterServiceImpl implements IUserRegisterService {

    @Autowired
    MemberMapper memberMapper;

    @Autowired
    UserVerifyMapper userVerifyMapper;

    @Autowired
    JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    String mailUsername;

    @Override
    public ResponseData register(UserRegisterRequest registerRequest) {
        // 判重
        if (userNameIsRepeat(registerRequest)) {
            return new ResponseUtil<>().setErrorMsg(UserRetCode.USERNAME_ALREADY_EXISTS.getMessage());
        }

        Date date = new Date();
        // 向用户表中插入一条记录
        int affectedRows = insertUser(registerRequest, date);
        if (affectedRows != 1) {
            return new ResponseUtil<>().setErrorMsg(UserRetCode.USER_REGISTER_FAILED.getMessage());
        }
        // 向用户验证表中插入一条记录
        String uuid = new AESUtil(registerRequest.getUserName() + UUID.randomUUID().toString()).encrypt().substring(0, 50);
        int verifyAffectedRows = insertUserVerify(registerRequest, date,uuid);
        if (verifyAffectedRows != 1) {
            return new ResponseUtil<>().setErrorMsg(UserRetCode.USER_REGISTER_VERIFY_FAILED.getMessage());
        }
        // 发送激活邮件
        sendVerifyMail(registerRequest,uuid);

        // 打印日志
        log.info("用户注册成功，注册参数{}", JSON.toJSONString(registerRequest));
        return new ResponseUtil<>().setData(null, UserRetCode.SUCCESS.getMessage());
    }

    private boolean userNameIsRepeat(UserRegisterRequest registerRequest) {
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username", registerRequest.getUserName());

        // 判断用户是否已存在
        List<Member> members = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(members)) {
            return true;
        }
        return false;
    }

    private int insertUser(UserRegisterRequest registerRequest, Date date) {
        Member member = new Member();
        member.setUsername(registerRequest.getUserName());
        // 密码加密
        String userPwd = new AESUtil(registerRequest.getUserPwd()).encrypt();
        member.setPassword(userPwd);
        member.setEmail(registerRequest.getEmail());
        member.setCreated(date);
        member.setUpdated(date);
        member.setIsVerified("N");
        return memberMapper.insertSelective(member);
    }

    private int insertUserVerify(UserRegisterRequest registerRequest, Date date,String uuid) {
        UserVerify userVerify = new UserVerify();
        userVerify.setUsername(registerRequest.getUserName());
        userVerify.setRegisterDate(date);
        // 拼接上用户名保证UUID不重复
        // String uuid = new AESUtil(registerRequest.getUserName() + UUID.randomUUID().toString()).encrypt().substring(0, 50);
        userVerify.setUuid(uuid);
        userVerify.setIsVerify("N");
        userVerify.setIsExpire("N");
        return userVerifyMapper.insertSelective(userVerify);
    }

    private void sendVerifyMail(UserRegisterRequest registerRequest,String uuid) {
        // 启动子线程
        new Thread() {
            @Override
            public void run() {
                SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
                simpleMailMessage.setSubject("您已注册成功，请点击下方链接激活！");
                // String uId = UUID.randomUUID().toString();
                String userName = registerRequest.getUserName();
                String url = "http://localhost:9999/user/verify?uuid="+uuid+"&username="+userName;
                simpleMailMessage.setText(url);
                simpleMailMessage.setFrom(mailUsername);
                simpleMailMessage.setTo(registerRequest.getEmail());
                mailSender.send(simpleMailMessage);
            }
        }.start();
    }

    /**
     * @description: 用户注册模块的邮件激活功能
     * @param request
     * @author : Zqp
     * @version :
     * @date : 2023/1/10 17:16
     */
    @Override
    public void verify(UserVerifyRequest request) {

        updateUserVerifyState(request);

        log.info("用户激活成功，激活时间{}", new Date(System.currentTimeMillis()));

    }

    private void updateUserVerifyState(UserVerifyRequest request) {
        @NotEmpty String username = request.getUsername();
        @NotEmpty String uuid = request.getUuid();

        // 根据条件更新数据库
        UserVerify userVerify = new UserVerify();
        userVerify.setIsVerify("Y");

        // todo 此处暂时不设置激活时限
        // userVerify.setRegisterDate(new Date(System.currentTimeMillis()));

        Example userVerifyExample = new Example(UserVerify.class);
        userVerifyExample.createCriteria()
                .andEqualTo("username",username)
                .andEqualTo("uuid",uuid)
                .andEqualTo("isVerify","N");
        int affectedRows1 = userVerifyMapper.updateByExampleSelective(userVerify,userVerifyExample);

        // 如果更新失败，则抛出异常
        if (affectedRows1 !=1) {
            throw new ValidateException(UserRetCode.VERIFY_FAILED.getCode(),UserRetCode.VERIFY_FAILED.getMessage());
        }

        // 更新成功则继续更新Member表中的激活信息
        Member member = new Member();
        member.setUpdated(new Date(System.currentTimeMillis()));
        member.setIsVerified("Y");

        Example memberExample = new Example(Member.class);
        memberExample.createCriteria().andEqualTo("username",username);

        int affectedRows2 = memberMapper.updateByExampleSelective(member, memberExample);

        // 如果更新失败，则抛出异常
        if (affectedRows2 !=1) {
            throw new ValidateException(UserRetCode.VERIFY_FAILED.getCode(),UserRetCode.VERIFY_FAILED.getMessage());
        }

    }
}
